package com.may.wind.service;

import com.may.wind.dao.BookRepository;
import com.may.wind.entity.Book;
import com.may.wind.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    BookRepository bookRepository;
    @Autowired
    CategoryService categoryService;

    public List<Book> getList() {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return bookRepository.findAll(sort);
    }

    public void addOrUpdate(Book book) {
        bookRepository.save(book);
    }

    public void deleteById(long id) {
        bookRepository.deleteById(id);
    }

    public List<Book> getListByCategory(int categoryId) {
        Category category = categoryService.get(categoryId);
        return bookRepository.findAllByCategory(category);
    }

    public List<Book> searchBooks(String keywords) {
        return bookRepository.findAllByTitleLikeOrAuthorLike('%' + keywords + '%', '%' + keywords + '%');
    }
}
